import Vue from 'vue';
import VueRouter from 'vue-router';
import Auth from '@/views/Auth.vue';
import User from '@/views/User.vue';
import store from '@/store/index.js';
// import UserList from '@/components/UserList.vue'
// import ArticleList from '@/components/ArticleList.vue'
// import NotificationList from '@/components/NotificationList.vue'
// import LikeList from '@/components/LikeList.vue'
import Article from '@/views/ArticleDetail.vue';
import ArticleList from '@/components/ArticleList.vue';
import Home from '../views/Home.vue';
import NotFound from '../views/404.vue'
import ServerError from '../views/500.vue'
import Notifications from '../views/Notifications.vue'
import Security from '../views/Security.vue'
import EmailValidationConfirm from '../views/EmailValidationConfirm.vue'
import ResetPassword from '../views/ResetPassword.vue'

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
  },
  {
    path: '/auth',
    name: 'Auth',
    component: Auth,
  },
  {
    path: '/user/:id',
    name: 'User',
    component: User,
  },
  {
    path: '/article/:id',
    name: 'Article',
    component: Article,
  },
  {
    path: '/articles',
    name: 'ArticleList',
    component: ArticleList,
  },
  {
    path: '/notifications',
    name: 'Notifications',
    component: Notifications,
    meta: {
      requireAuth: true
    }
  },
  {
    path: '/security',
    name: 'Security',
    component: Security,
    meta: {
      requireAuth: true
    }
  },
  {
    path: '/ResetPassword',
    name: 'ResetPassword',
    component: ResetPassword,
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue'),
  },
  {
    path: '/emailValidationConfirm',
    name: 'EmailValidationConfirm',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: EmailValidationConfirm,
  },
  {
    path: '/404',
    name: '404',
    component: NotFound,
  },
  {
    path: '/500',
    name: '500',
    component: ServerError,
  },
];

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
});

router.beforeEach((to, from, next) => {
  const { token } = localStorage;
  const login = token != undefined;
  if (store.state.login != login) {
    store.commit('setLogin', login);
  }
  if (to.meta.requireAuth && !store.state.login) {
    next({ name: 'Auth', params: { msg: '请先登录或注册' } })
  } else {
    next();
  }
});

export default router;
